<?php
namespace app\index\controller;

use think\Controller;
use think\Cache;
use think\Request;
use think\Config;
use think\Session;
use think\Log;
use xcx_weixin\WXBizMsgCrypt;


class Xcxweixin extends Controller
{

    function __construct() {
        parent::__construct();
        Config::load(APP_PATH.'other.php');
        $config = Config::get('xcxweixin');//微信小程序消息推送

        $this->AppID = $config['AppID'];//小程序ID
        $this->AppSecret = $config['AppSecret'];//小程序密钥
        $this->Token = $config['Token'];//Token(令牌)
        $this->EncodingAESKey = $config['EncodingAESKey'];//消息加密密钥
    }

    //验证
    public function xcx_verification(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $openid  = $_GET["openid"];
        $encrypt_type  = $_GET["encrypt_type"];
        $msg_signature  = $_GET["msg_signature"];
        $sReqData = file_get_contents("php://input"); //接收post数据
        Log::record($sReqData);

        //调用微信下载的那个类包
        $wxcpt = new \xcx_weixin\WXBizMsgCrypt($this->Token, $this->EncodingAESKey,  $this->AppID);
        $wxcpt->WXBizMsgCrypt($this->Token, $this->EncodingAESKey,  $this->AppID);

        $sMsg = "";  // 解析之后的明文
        $errCode = $wxcpt->DecryptMsg($msg_signature, $timestamp, $nonce, $sReqData, $sMsg);

        if ($errCode == 0) {
//            Log::record($sMsg);
            // 解密成功，sMsg即为xml格式的明文
            $sMsg=html_entity_decode($sMsg);
            $xml = new \DOMDocument();
            $xml->loadXML($sMsg);

            $ToUserName = $xml->getElementsByTagName('ToUserName')->item(0)->nodeValue;//小程序的id
            $FromUserName = $xml->getElementsByTagName('FromUserName')->item(0)->nodeValue;//发送人的openid
            $CreateTime = $xml->getElementsByTagName('CreateTime')->item(0)->nodeValue;//发送时间(时间戳)
            $MsgType = $xml->getElementsByTagName('MsgType')->item(0)->nodeValue;//消息格式

            if($MsgType=='event'){//时间处理
                $Event = $xml->getElementsByTagName('Event')->item(0)->nodeValue;//消息事件
                $SessionFrom = $xml->getElementsByTagName('SessionFrom')->item(0)->nodeValue;//可以理解成标识
                Log::record($SessionFrom);

                if($Event=='user_enter_tempsession'){//用户点击小程序在线客服以后触发的事件
                    if($SessionFrom==1){
                        $reply_info['content'] = '标识是1！';
                    }else{
                        $reply_info['content'] = '欢迎进入在线客服，我们有专人为您解答！';
                    }
                }
            }elseif($MsgType=='text') {
                $Content = $xml->getElementsByTagName('Content')->item(0)->nodeValue;//消息内容
                $MsgId = $xml->getElementsByTagName('MsgId')->item(0)->nodeValue;//消息id
                $reply_info['content'] = '你发送内容是:' . $Content;
            }else{
                $reply_info['content'] = '只支持文本消息！';
            }
            $reply_info['openid'] = $FromUserName;
            $this->xcxweixin_reply_news($reply_info);
        } else {

            print("ERR: " . $errCode . "\n\n");
        }
    }
    //消息回复
    function xcxweixin_reply_news($reply_info){
        $access_token = $this->xcxweixin_get_accesstoken();
        $this->xcxweixin_typing($reply_info['openid']);//输入中的状态
        $reply_data['touser'] = $reply_info['openid'];
        $reply_data['msgtype'] = 'text';//文本消息
        if($reply_data['msgtype']=='text'){
            $reply_data['text']['content'] = $reply_info['content'];
        }
        $data_post_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
        $result = json_decode(http_curl($data_post_url,'POST',json_encode($reply_data,JSON_UNESCAPED_UNICODE)));
        if($result->errcode==0){
            return 1;
        }
    }
    //输入中的状态
    function xcxweixin_typing($openid){
        $access_token = $this->xcxweixin_get_accesstoken();
        $typing_data['touser'] = $openid;
        $typing_data['command'] = 'Typing';//"Typing"：对用户下发“正在输入"状态；"CancelTyping"：取消对用户的”正在输入"状态
        $data_post_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/typing?access_token='.$access_token;
        $result = json_decode(http_curl($data_post_url,'POST',json_encode($typing_data)));
    }

    //获取小程序的accesstoken
    function xcxweixin_get_accesstoken(){
        Cache::set('access_token','');
        $access_token = Cache::get('access_token');
        if(!$access_token){
            $get_token_url ='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->AppSecret;
            $result = json_decode(http_curl($get_token_url));
            $access_token = $result->access_token;
            Cache::set('access_token',$access_token,7000);
        }
        return $access_token;
    }
}


